﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading.Tasks;
using System.Threading;
using System.Diagnostics;
using System.Data.SqlClient;
namespace SqlQueryAnalyzer
{
    public partial class SqlQueryForm : BaseForm
    {
        SqlConnection conn;
        Task task;
        public bool IsUserCancled = false;
        public SqlQueryForm()
        {
            InitializeComponent();
            Util.SetTilte(this);
        }       

        private void QueryAnalysisForm_Load(object sender, EventArgs e)
        {
            this.ddlDatabase.DataSource = SqlStructQuery.GetDatabases();
        }

        private void btnExecute_Click(object sender, EventArgs e)
        {
            try
            {
                SetBtnStatus(false);
                string sql = this.txtSQL.Text.ToLower();
                string database = this.ddlDatabase.SelectedValue.ToString();
                task = Task.Factory.StartNew(() =>
                {
                    string message = null;
                    int recordCount = 0;
                    DataTable dt = null;
                    Stopwatch watch = new Stopwatch();
                    watch.Start();
                    try
                    {
                        conn = new SqlConnection(Util.ConnectionString.Replace("master", database));
                        conn.Open();
                        if (sql.Contains("insert ") || sql.Contains("update ") || sql.Contains("delete "))
                        {
                            recordCount = DbHelperSQL.ExecuteNonQuery(conn, sql);
                        }
                        else
                        {
                            dt = DbHelperSQL.GetDataTable(conn, sql);
                            recordCount = dt.Rows.Count;
                        }
                    }
                    catch (Exception ex)
                    {
                        message = ex.GetBaseException().Message;
                    }
                    try
                    {
                        if (conn != null && conn.State != ConnectionState.Closed)
                        {
                            conn.Close();
                        }
                    }
                    catch (Exception ex)
                    {
                        message = ex.GetBaseException().Message;
                    }


                    watch.Stop();
                    this.Invoke(new MethodInvoker(() =>
                    {
                        this.lblRecordCount.Text = string.Format("影响记录数:{0}", recordCount.ToString("#,##"));
                        this.lblExecuteTime.Text = string.Format("执行时间:{0}秒", watch.Elapsed.TotalSeconds.ToString("0.00"));
                        this.dataGrid.DataSource = dt;
                        if (!IsUserCancled && !string.IsNullOrEmpty(message))
                        {
                            MessageBox.Show(message, "发生异常", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                        SetBtnStatus(true);

                    }));
                });

                StartTimer();
            }
            catch (Exception ex)
            {
                SetBtnStatus(true);
                MessageBox.Show(ex.Message);
            }
            finally
            {
                if (conn != null)
                    conn.Close();
            }
        }

        private void StartTimer()
        {
            Task.Factory.StartNew(() =>
            {
                int second = 0;
                while (task.Status == TaskStatus.Running || task.Status == TaskStatus.Running)
                {
                    this.Invoke(new MethodInvoker(() =>
                    {
                        this.btnTiming.Text = string.Format("计时器({0})", second);
                    }));
                    Thread.Sleep(1000);
                    second++;
                }
            });
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            try
            {
                IsUserCancled = true;
                conn.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.GetBaseException().Message);
            }
            SetBtnStatus(true);
        }

        private void SetBtnStatus(bool enableExecute)
        {
            this.btnExecute.Text = "执行";
            this.btnStop.Text = "停止";
            if (enableExecute)
            {
                this.btnExecute.Enabled = true;
                this.btnStop.Enabled = false;
            }
            else
            {
                this.btnExecute.Enabled = false;
                this.btnStop.Enabled = true;
            }
        }

        private void txtSQL_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Modifiers == Keys.Control && e.KeyCode == Keys.A)
            {
                ((TextBox)sender).SelectAll();
            }
        }

        private void menuAbout_Click(object sender, EventArgs e)
        {
            new AboutForm().ShowDialog();
        }

        private void menuLog_Click(object sender, EventArgs e)
        {
            new LogForm().ShowDialog();
        }

        private void menuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {

        }
    }
}
